package com.changwu.cwbase;

import android.app.Activity;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.support.multidex.MultiDexApplication;

import com.blankj.utilcode.util.Utils;
import com.bumptech.glide.Glide;
import com.changwu.cwbase.db.DaoMaster;
import com.changwu.cwbase.db.DaoSession;
import com.changwu.cwbase.util.PreferencesUtil;
import com.lljjcoder.citywheel.CityConfig;
import com.lljjcoder.style.citypickerview.CityPickerView;

import java.util.LinkedList;
import java.util.List;

public class App extends MultiDexApplication {
    private static CityPickerView mPicker = new CityPickerView();
    private static App app;
    public static final boolean ENCRYPTED = false;
    private Context mcontext;
    private static DaoSession daoSession;
    //读取本地文件权限
    public boolean isHasReadPermission = false;
    /**
     * 所有activity集合
     */
    private List<Activity> activities = new LinkedList<Activity>();

    @Override
    public void onCreate() {
        super.onCreate();
        initControllers();
        initApp();
    }

    private void initControllers() {
        Controllers.sLogSwitch = true;
        Controllers.customTagPrefix = "cwbase";
        Controllers.preferencesName = "cwbase";
    }

    private void initApp() {
        app = this;
        Utils.init(this);
        Glide.with(this);
        PreferencesUtil.ensureInit(this);
        CityConfig cityConfig = new CityConfig.Builder().build();
        mPicker.setConfig(cityConfig);
        mPicker.init(this);
        //配置数据库
        setupDatabase();
    }

    /**
     * 配置数据库
     */
    private void setupDatabase() {
        //创建数据库shop.db"
        DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(this, "cw.db", null);
        //获取可写数据库
        SQLiteDatabase db = helper.getWritableDatabase();
        //获取数据库对象
        DaoMaster daoMaster = new DaoMaster(db);
        //获取Dao对象管理者
        daoSession = daoMaster.newSession();
    }

    public static DaoSession getDaoInstant() {
        return daoSession;
    }

    /**
     * 增加Activity
     */
    public void addActivity(Activity activity) {
        activities.add(activity);
    }

    public void finishActivity(Activity activity) {
        if (activity != null) {
            this.activities.remove(activity);
            activity.finish();
            activity = null;
        }
    }

    /**
     * 退出系统时，结束掉所有Activity
     */
    public void exit() {
        for (Activity activity : activities) {
            if (activity != null) {
                activity.finish();
            }
        }
    }

    public static App getInstance() {
        return app;
    }

    public CityPickerView getCityPicker() {
        return mPicker;
    }
}